package com.dao;

import com.dao.CourseDAO;
import com.model.Course;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.dao.EmptyResultDataAccessException;

import java.sql.ResultSet;
import java.util.List;

@Repository
public class CourseDAOImpl implements CourseDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 定义 SQL 语句
    private static final String SQL_FIND_ALL = "SELECT * FROM course";
    private static final String SQL_FIND_BY_ID = "SELECT * FROM course WHERE course_id = ?";
    private static final String SQL_INSERT = "INSERT INTO course (course_name, teacher, course_time, course_state) VALUES (?, ?, ?, ?)";
    private static final String SQL_UPDATE = "UPDATE course SET course_name = ?, teacher = ?, course_time = ?, course_state = ? WHERE course_id = ?";
    private static final String SQL_DELETE = "DELETE FROM course WHERE course_id = ?";

    //  RowMapper 将 ResultSet 中的每一行数据转换成一个 Course 对象
    private static final RowMapper<Course> ROW_MAPPER = (ResultSet rs, int rowNum) -> {
        Course course = new Course();
        course.setCourseId(rs.getInt("course_id"));
        course.setCourseName(rs.getString("course_name"));
        course.setTeacher(rs.getString("teacher"));
        course.setCourseTime(rs.getString("course_time"));
        course.setCourseState(rs.getString("course_state"));
        return course;
    };

    // CRUD 方法

    /* 查找全部 */
    @Override
    public List<Course> findAll() {
        return jdbcTemplate.query(SQL_FIND_ALL, ROW_MAPPER);
    }

    /* 根据课程ID查找 */
    @Override
    public Course findById(Integer id) {
        try {
            return jdbcTemplate.queryForObject(SQL_FIND_BY_ID, new Object[]{id}, ROW_MAPPER);
        } catch (EmptyResultDataAccessException e) {
            return null; // 或者抛出自定义异常
        }
    }

    /* 添加新的课程信息 */
    @Override
    public void save(Course course) {
        jdbcTemplate.update(SQL_INSERT,
                course.getCourseName(),
                course.getTeacher(),
                course.getCourseTime(),
                course.getCourseState());
    }
    /* 更新课程信息 */
    @Override
    public void update(Course course) {
        jdbcTemplate.update(SQL_UPDATE,
                course.getCourseName(),
                course.getTeacher(),
                course.getCourseTime(),
                course.getCourseState(),
                course.getCourseId());
    }

    /* 根据id删除课程信息 */
    @Override
    public void deleteById(Integer id) {
        jdbcTemplate.update(SQL_DELETE, id);
    }
}